package com.example.email.utils;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;

public class DelayQueue {

    private RedisTemplate<String,String> redisTemplate=new RedisTemplate<>();
    private String queueKey;


    public  DelayQueue(RedisTemplate<String,String> redisTemplate,String queueKey){
        this.redisTemplate = redisTemplate;
        this.queueKey=queueKey;
    }


    public void put(String id,long delay){
        //延时多久，获取到当前的时间+你想延时多久
        long timestamp= System.currentTimeMillis()+delay;
        redisTemplate.opsForZSet().add(queueKey,id,timestamp);
    }

    /**
     * 取消任务
     * @param id 任务
     */
    public void cancel(String id){
        redisTemplate.opsForZSet().remove(queueKey,id);
    }


    public void start(){
        new Thread(()->{
            //处理队列
            while (true) {
                //拿到任务
                Set<ZSetOperations.TypedTuple<String>> typedTuples = redisTemplate.opsForZSet().rangeByScoreWithScores(
                        queueKey,
                        0,
                        System.currentTimeMillis(),
                        0,
                        1
                );
                //执行任务-先确保拿到了任务
                if(!typedTuples.isEmpty()){
                    ZSetOperations.TypedTuple<String> next = typedTuples.iterator().next();
                    //被处理的任务要从队列中移除
                    redisTemplate.opsForZSet().remove(queueKey,next.getValue());
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String format = sdf.format(new Date());
                    System.out.println("正在执行任务："+next.getValue()+"at:"+format);
                }

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }



}
